package systempen.cmanager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class TypesBrowser extends ListActivity {
	ListActivity thisclass;
	//private String[] lv_arr;
	public OnItemClickListener kl;
	public OnClickListener No;
	public View arg;
	public ListView lv;
	public String sentCostCode;
	public View poslati;
	public View poslati2;
	public View poslati3;
	public String param1;
	public String Level;
	public String classSender; //class that invoked browser
	public String Name;
	public String selectedWord; 
	//public String parent;

	@Override
	 public void onCreate(Bundle icicle){
			super.onCreate(icicle);
			ThemePicker.onActivityCreateSetTheme(this);
	        setContentView(R.layout.typesbrowser);
			try{
			Bundle bun = getIntent().getExtras();
			thisclass = this;
			Level = bun.getString("Level");
			Button bPath = (Button)findViewById(R.id.ButPath);
			bPath.setText(getPathOfLevel(Level));
			classSender = bun.getString("classSender");
			if (bun.getString("Name")!=null)
				Name = bun.getString("Name");
			//ArrayList<String> results = new ArrayList<String>();
			thisclass = this;
			lv = getListView();
			registerForContextMenu(lv);
			attachEvent();
			fillList();
			}//od try
			catch(Exception ex) 
			{
				Toast.makeText(this,"FFS: "+ex.getMessage(), Toast.LENGTH_LONG).show();
			}
			
	}
	public String getPathOfLevel(String levelID){// duplikat sa CostTypes.java trebalo mi je 4 sata za ovo, al sam izlapio... note to self: sledeci put iskopiraj, konju!
		String parent = util.parentLevelExists(levelID,thisclass);
		if (parent!=""){//ako postoji parent daj ga ako ne onda to je to
			String povratni = getPathOfLevel(parent) +" > "+util.getLevelName(levelID,thisclass);
			return povratni;
		}else{
			if (levelID.equals("0")){
				levelID = "Root";
			}
			return levelID;
		}
	}
	public String parentLevelExistss(String levelID){//obrisati
		return "";
	}
	public void attachEvent(){
		kl = new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				//if there are child costs than open them
				poslati = ((RelativeLayout) arg1).findViewById(R.id.ctcode);
				String k =((TextView)poslati).getText().toString(); 
				if ((util.existsChildCost(k,thisclass )==true))//if exists child - open again lower level
				{
					//call your self with that parameter
					//startActivity(new Intent(this, CostTypes.class));
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setClassName(thisclass, TypesBrowser.class.getName());
					Bundle bun = new Bundle();
					bun.putString("Level", ((TextView)poslati).getText().toString());
					bun.putString("classSender", classSender.toString());
					bun.putString("Name", Name);//send name of type
					intent.putExtras(bun);
					startActivity(intent);
				}else { 
					//addAlertDialog(arg1);//ask to add type
					//vrati se activity koji te pozvao i vrati mu parametre:
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setClassName(thisclass, classSender.toString());
					Bundle bun = new Bundle();
					bun.putString("Level", ((TextView)poslati).getText().toString());
					bun.putString("classSender", classSender.toString());
					bun.putString("Name", Name);//send name you accepterd prolazna promenjiva
					bun.putString("TypeName", ((TextView)poslati).getText().toString());//send name of type to sto si nasao
					intent.putExtras(bun);
					startActivity(intent);
				}
			}};
		lv.setOnItemClickListener(kl);
	}
	public void addAlertDialog(View arg1){
		arg = arg1;
		AlertDialog.Builder alt_bld = new AlertDialog.Builder(TypesBrowser.this);
		poslati = ((RelativeLayout) arg1).findViewById(R.id.ctgornji);
		poslati2 = ((RelativeLayout) arg1).findViewById(R.id.ctdonji);
		poslati3 = ((RelativeLayout) arg1).findViewById(R.id.ctcode);
		
		alt_bld.setMessage("Attach Cost to Type: "+((TextView)poslati).getText().toString()/*+" "+((TextView)poslati3).getText().toString()*/)
		//.setCancelable(false)
		.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int id) {
		// Action for 'Yes' Button
			util.execSQL("INSERT INTO cost_type(name,parent) values ('"+Name.toString()+"',"+((TextView)poslati3).getText().toString()+")", thisclass);
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setClassName(thisclass, CostList.class.getName());
			thisclass.startActivity(intent);
		}
		})
		.setNegativeButton("No", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int id) {
		//  Action for 'NO' Button
		dialog.cancel(); 
		}
		});
		alt_bld.setCancelable(false);
		No = new OnClickListener() {
			public void onClick(DialogInterface dialog, int id){
				dialog.cancel();}
		};
		alt_bld.setNegativeButton("No", No); 
		AlertDialog alert = alt_bld.create();
		// Title for AlertDialog
		alert.setTitle(" type?");
		// Icon for AlertDialog
		alert.setIcon(R.drawable.help);
		alert.show();

	}
	
	public void fillList(){
		ArrayList<CostListItem> m_Devices = new ArrayList<CostListItem>();
		SQLiteDatabase db;
		Cursor c;
        List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
        db = this.openOrCreateDatabase(getApplicationContext().getDatabasePath("DBS").toString(), android.content.Context.MODE_PRIVATE , null);
		c = db.rawQuery("select name as name, code as _id, code as code from cost_type where parent ="+Level.toString(),null);

		c.moveToFirst();
		int i = c.getCount();
		if (i==0){
			c = null;
			//c = db.rawQuery("select ' No types in database, please add type via menu.' as _id, 0 as _id2, o as _id3", null);
			// ako nije nasao tipove, nema filozofije - samo insert sa 0
			util.execSQL("INSERT INTO cost_type(name,parent) values ('"+Name.toString()+"',0)", thisclass);
			//fillList(); //pozovi se sam, sada ces imati nesto u bazi. Nemoj se pozivati vise ako Boga znas, insertovao si sto se od tebe trazilo i sada razlaz!
		}
		if (c.getCount()>0){
		 if (c.moveToFirst()) {
             CostListItem device;
			 do {
				 //String mC = c.getString(0);
				 HashMap<String, String> map = new HashMap<String, String>();
				 map.put("name",c.getString(1)+c.getString(0));
				 String numberOfSubrtpes = util.getSubtypes(c.getString(2).toString(),this);
				 if (numberOfSubrtpes  == null)
						 numberOfSubrtpes = "0";
				 String suma="";
				 suma = util.getCostSum(c.getString(2).toString(), this,"");
				 //if (suma == null) premesteno u util
				 //	suma = "0";
				 //map.put("_id","Number of subtypes: "+numberOfSubrtpes.toString());
				 map.put("_id","Sum of subtypes: "+suma);
				 map.put("code",c.getString(2));
				 fillMaps.add(map);
				 //strings.add(mC); //cemu ovo sluzi?
				 String gornji  = c.getString(0);
				 String donji  = "";//suma;
				 String code  = c.getString(2);
				 String cifra = suma;
				 String opis = "";
                 if (util.existsChildCost(code, getApplicationContext())){
		            	opis = "Contains subtypes";
                 }
				 device =new CostListItem();// new ListItemL(gornji,donji,code,cifra,opis,"","","");
				 device.setGornji(gornji);
				 device.setDonji(donji);
				 device.setCode(code);
				 device.setCifra(cifra);
				 device.setOpis(opis);
				 device.setType("");
				 device.setPath("");
				 device.setOpis2("");
				 
				 m_Devices.add(device);
				 }while (c.moveToNext()); 
			 //lv_arr = (String[]) strings.toArray(new String[strings.size()]); 
			 } 
		 }
		CostListAdapter lvAdapter =  new CostListAdapter(this, R.layout.costlist_row, m_Devices);
		this.setListAdapter(lvAdapter);
		c.close();
		db.close();
	}
	
	@Override //pressed back button cya
	public boolean onKeyDown(int keyCode, KeyEvent event)  {
	    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
	    		startActivity(new Intent(thisclass, MainActivityTab.class)); 
	        return true;
	    }
    return super.onKeyDown(keyCode, event);
	} 

	
	public void onSelectThisLevel(View view)
	{
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setClassName(thisclass, classSender.toString());
		Bundle bun = new Bundle();
		bun.putString("Level", Level.toString());
		bun.putString("classSender", classSender.toString());
		bun.putString("Name", Name);//send name you accepterd prolazna promenjiva
		bun.putString("TypeName", util.getLevelName(Level,getApplicationContext()));//send name of type to sto si nasao
		intent.putExtras(bun);
		startActivity(intent);
	}
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		try{
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
			LinearLayout ln = ((LinearLayout) info.targetView);
			View vi = ln.findViewById(R.id.ctcode);
	        selectedWord = ((TextView)vi).getText().toString();// ((TextView) info.targetView).getText().toString();
	        //selectedWordId = info.id;
			menu.setHeaderTitle(selectedWord);
			menu.add(0,v.getId(),0,"Delete Type");
			menu.add(0,v.getId(),0,"Delete cost");
		}
		catch (Exception ex){
			Toast.makeText(this,"types browser crete context menu: "+ex.getMessage(), Toast.LENGTH_LONG).show();
		}
	}
	@Override  
	public boolean onContextItemSelected(MenuItem item) {  
	    if(item.getTitle()=="Delete Type"){
	    	contextDelete(selectedWord);}  
	    else if(item.getTitle()=="Meni 2"){/*nema nista*/}  
	    else {return false;}  
	    return true;  
	}  

	public void contextDelete(String title){  
		try{
			//Toast.makeText(this, "function 1 called"+String.valueOf(id)+title, Toast.LENGTH_SHORT).show();
			util.execSQL("delete from cost_type where code = "+title, thisclass);
			lv.setAdapter(null);
		 	fillList();//functions like refresh();
		}
		catch (Exception ex){
			Toast.makeText(this,"pokusao obrisati code: "+util.getBracketValue(title)+" "+ex.getMessage(), Toast.LENGTH_LONG).show();
		}
	}

}
